<template>
    <el-drawer :title="`${title}作业`" custom-class="paper-drawer" :visible="open" direction="rtl" :size="1600" append-to-body @close="onClose">
      <div class="drawer-body">
        <div class="card mb-30">
          <el-input placeholder="请输入作业名称" v-model="form.name" />
        </div>
        <div class="row">
          <div class="left-col">
            <div class="card">
              <div class="tree-title">
                <span>题量：10，总分：100.0</span>
                <i class="el-icon-plus add-icon"></i>
              </div>
              <div class="module-node-wrap">
                <div class="tree-node module-node" @click="() => onTreeNodeChecked()">
                  <div class="node-label">一、听力理解</div>
                  <div class="node-right">
                    <i class="el-icon-plus"></i>
                    <i class="el-icon-edit"></i>
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
                <div class="tree-node desc-node" @click="() => onTreeNodeChecked()">
                  <div class="node-label">模块说明：每道题你都会听到一句话</div>
                  <div class="node-right">
                    <i class="el-icon-edit"></i>
                  </div>
                </div>
              </div>
              <div class="type-node-wrap">
                <div class="tree-node type-node" @click="() => onTreeNodeChecked()">
                  <div class="node-label">(一) 听句子（共2题，10.0分）</div>
                  <div class="node-right">
                    <i class="el-icon-plus"></i>
                    <i class="el-icon-edit"></i>
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
                <div class="tree-node desc-node" @click="() => onTreeNodeChecked()">
                  <div class="node-label">模块说明：每道题你都会听到一句话</div>
                  <div class="node-right">
                    <i class="el-icon-edit"></i>
                  </div>
                </div>
              </div>
              <div class="question-node-wrap selected" @click="() => onTreeNodeChecked()">
                <div class="tree-node question-node">
                  <div class="node-label">1 (5.0分) 仔细阅读题目并请正确回答问题</div>
                  <div class="node-right">
                    <i class="el-icon-edit"></i>
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="right-col">
            <div class="card mb-30">
              <div class="text-right">
                <span>从题库导入</span>
              </div>
              <div class="question-type">
                <label>一级题型</label>
                <el-radio-group v-model="questionForm.firstLevelType">
                  <el-radio-button v-for="item in firstLevelTypeOps" :key="item.value" :label="item.value">{{item.label}}</el-radio-button>
                </el-radio-group>
              </div>
              <div class="question-type">
                <label v-if="secondLevelTypeOps.length > 0">二级题型</label>
                <el-radio-group v-model="questionForm.secondLevelType" @input="onSecondTypeChange">
                  <el-radio-button v-for="item in secondLevelTypeOps" :key="item.value" :label="item.value">{{item.label}}</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="card">
              <div v-if="questionForm.formCode">
                <div class="question-head">
                  <span>听句子:</span>
                  <el-input v-model="questionForm.score" size="mini"></el-input>
                  <span>分</span>
                </div>
                <complex v-if="questionForm.formCode == 'Assembly'" :initialVals="questionForm" :clean="cleanInner" :validate="validate" @onChange="submitForm" />
                <basic v-else :initialVals="questionForm" :clean="cleanInner" :validate="validate" @onChange="submitForm" />
                <div class="pl-item">
                  <el-button type="primary">保存</el-button>
                  <el-button>重置</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="drawer-footer">
        <el-button type="primary" @click="triggerValidate">保存到考试库</el-button>
        <el-button @click="onClose">发 布</el-button>
      </div>
      <!-- 修改树节点对话框 -->
      <el-dialog title="编辑" @close="onDirClose" :visible.sync="editVisible" append-to-body modal-append-to-body>
        <el-input v-model="curNodeName" placeholder="请填写名称"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="onDirClose">取 消</el-button>
          <el-button type="primary" @click="onDirConfirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-drawer>
  </template>
  
  <script>
  import { addPaper, getPaperModuleTree } from '@/api/publicManage/homework';
  import { getQuestionTypeList } from '@/api/publicManage/questionBase';
  import { addQuestion, updateQuestion } from '@/api/publicManage/questionBase';
  import Basic from '@/views/publicManage/questionBase/components/basic.vue';
  import Complex from '@/views/publicManage/questionBase/components/complex.vue';
  
  export default {
    name: "PaperEditDrawer",
    props: {
      open: {
        type: Boolean,
        default: false,
      },
      libId: {
        type: Number,
        default: 0,
      },
      paperType: {
        type: String,
        default: ''
      },
      templateId: {
        type: String,
        default: ''
      },
      search: {
        type: Object,
        default: () => ({}),
      },
      initData: {
        type: Object,
        default: () => ({}),
      }
    },
    components: { Basic, Complex },
    data() {
      return {
        title: "新增",
        firstLevelTypeOps: [],
        secondLevelTypeOps: [],
        form: {
          id: '',
          name: '',
          moduleTree: [],
        },
        questionForm: {},
        validate: '',
        cleanInner: '',
        editVisible: false,
        curNodeName: '',
      }
    },
    watch: {
      open: {
        handler(val) {
          if (val && !this.initData.id) {
            const { search: { isPublic, courseId }, libId, paperType, templateId } = this;
            const formData = { isPublic, courseId, libId, paperType };
            if (templateId) formData.templateId = templateId;
            addPaper(formData).then(({ code, data }) => {
              if (code === 200) {
                const { id, name } = data;
                this.form  = { ...this.form, id, name };
              }
            });
          }
        }
      },
      initData: {
        handler(val) {
          if (val.id) {
            getPaperModuleTree(val.id).then(({ code, data }) => {
              if (code === 200) {
                this.form.moduleTree = data;
              }
            });
            // let formData = { ...this.questionForm, ...val };
            // let temp = {};
            // const { definition, answer, analysis } = formData.questionDetail || {};
            // formData.difficulty = String(val.difficulty);
            // if (formData.formCode === "Assembly") {
            //   const { items } = JSON.parse(definition);
            //   temp.items = items.map((item, index) => ({ ...item, answer: JSON.parse(answer).items[index] }));
            // } else {
            //   if (definition) temp = JSON.parse(definition);
            //   if (answer) temp.answer = JSON.parse(answer);
            // }
            // if (analysis) temp.analysis = analysis;
            // if (Object.keys(temp).length > 0) {
            //   formData = { ...formData, ...temp };
            //   delete formData.questionDetail;
            // }
            // this.questionForm = formData;
            // this.title = '编辑';
          }
        }
      },
      'questionForm.firstLevelType': {
        handler(val) {
          if (val) {
            const params = { typeLevel: 2, parentId: val };
            getQuestionTypeList(params).then(({ code, data }) => {
              if (code === 200) {
                this.secondLevelTypeOps = data.map(item => ({
                  label: item.name,
                  value: item.id,
                  formCode: item.formCode,
                }));
              }
            });
          }
        }
      }
    },
    created() {
      this.fetchFirstTypeList()
    },
    methods: {
      onTreeNodeChecked(name = '') {
        this.editVisible = true;
        this.curNodeName = name;
      },
      onDirClose() {
        this.editVisible = false;
        this.curNodeName = '';
      },
      onDirConfirm() {
        this.editVisible = false;
        console.log(this.curNodeName);
        this.curNodeName = '';
      },
      fetchFirstTypeList() {
        const params = { typeLevel: 1 };
        getQuestionTypeList(params).then(({ code, data }) => {
          if (code === 200) {
            this.firstLevelTypeOps = data.map(item => ({ label: item.name, value: item.id }));
          }
        })
      },
      onSecondTypeChange(val) {
        const result = this.secondLevelTypeOps.find(item => item.value === val);
        if (result) {
          console.log(result.formCode);
          this.questionForm = { ...this.questionForm, formCode: result.formCode };
          this.triggerClean();
        }
      },
      onClose() {
        this.questionForm = {};
        this.secondLevelTypeOps = [];
        this.$emit('update:open', false);
      },
      onSave() {
        // TODO: 调用保存接口
        console.log('提交数据');
        this.onClose();
      },
      filterObjShallow(obj) {
        const result = {};
        Object.keys(obj).map(item => {
          if (!['', null, undefined].includes(obj[item])) {
            result[item] = obj[item];
          }
        });
        return result;
      },
      // 清空内层表单
      triggerClean() {
        this.cleanInner = String(Date.now());
      },
      // 内层表单校验结果
      handleValid(isValid) {
        console.log(isValid);
      },
      // 触发表单验证
      triggerValidate() {
        this.validate = String(Date.now());
      },
      // 表单提交
      submitForm(data) {
        const formData = this.filterObjShallow(data);
        formData.difficulty = data.difficulty * 1;
        formData.questionDetail = {};
        const definition = {};
        if (data.descrips) {
          definition.descrips = data.descrips;
          delete formData.descrips;
        }
        if (data.options) {
          definition.options = data.options;
          delete formData.options;
        }
        if (data.options1) {
          definition.options1 = data.options1;
          delete formData.options1;
        }
        if (data.options2) {
          definition.options2 = data.options2;
          delete formData.options2;
        }
        if (data.items) {
          const items = [];
          definition.items = data.items.map(item => {
            items.push(JSON.parse(JSON.stringify(item.answer)));
            delete item.answer;
            return item;
          });
          data.answer = { items };
          delete formData.items;
        }
        if (Object.keys(definition).length > 0) {
          formData.questionDetail.definition = JSON.stringify(definition);
        }
        if (data.answer) {
          formData.questionDetail.answer = JSON.stringify(data.answer);
          delete formData.answer;
        }
        if (data.analysis) {
          formData.questionDetail.analysis = data.analysis;
          delete formData.analysis;
        }
        let submitFunc = addQuestion;
        if (formData.id) submitFunc = updateQuestion;
        submitFunc(formData).then(() => {
          this.$message({
            type: 'success',
            message: '题目保存成功'
          });
        });
      },
    }
  }
  </script>
  
  <style lang="scss" scoped>
  @import './index.scss';
  </style>
  